﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Claims;
using System.IdentityModel.Tokens;
using System.Linq;
using System.ServiceModel.Security.Tokens;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Practices.JsonWebToken {
    public partial class Validate : System.Web.UI.Page {
        protected void Page_Load(object sender, EventArgs e) {
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            // 密钥，需更改为可配置项
            string securityKey = "OUe6jxKjYRLaEuxK6SklUjLU0MSfZK7+0Qf5hDVOAG4";
            // 令牌，通过POST方式 以"SPAppToken"参数传输
            //string securityToken = Request["SPAppToken"];
            string securityToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6IjUwMDA3NzYwIn0.wXNjRCRj2vNKemaVzusWcH2fTgGAb4gRr_mazmTGJvI";

            var validationParameters = new TokenValidationParameters() {
                ValidAudience = "http://rmuep.erp.petrochina",
                ValidIssuer = "self",
                RequireExpirationTime = true,
                IssuerSigningToken = new BinarySecretSecurityToken(System.Text.Encoding.UTF8.GetBytes(securityKey)),
            };

            SecurityToken validatedToken;
            try {
                var principal = tokenHandler.ValidateToken(securityToken, validationParameters, out validatedToken);
                // 输出用户标识 （8位员工编号）
                Response.Write(principal.Identity.Name);
            } catch (Exception ex) {
                // 输出异常验证信息
                Response.Write(ex.Message);
            }            
        }
    }
}